package com.cx.base.day25_Rocketmq.producer.asyncProducer;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

/**
 * @Author: songyahui
 * @Date: 2020/9/27 20:42
 * @Version 1.0
 */
public class AsyncProducer {
    public static void main(String[] args) throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException {
//        实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("group1");
//        超时时间
        producer.setSendMsgTimeout(10000);
//        设置namesrv
        producer.setNamesrvAddr("192.168.48.128:9876;192.168.48.137:9876");
//        producer.setNamesrvAddr("106.52.131.197:9876;47.96.165.93:9876");
//        启动producer实例
        producer.start();
        producer.setRetryTimesWhenSendAsyncFailed(0);
        int i = 0;
        for (; i < 100; i++) {
            final int index = i;
//            创建消息，并且制定topic,tag和消息体
            Message msg = new Message("base", "tag_async", "orderID189", "hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
//            SendCallback接收异步返回结果的回调
            producer.send(msg, new SendCallback() {

                @Override
                public void onSuccess(SendResult sendResult) {
                    System.out.println("success:" + sendResult);
                }

                @Override
                public void onException(Throwable throwable) {
                    System.out.println(throwable);
                }
            });
        }
        TimeUnit.SECONDS.sleep(1);
        System.out.println("i=" + i);
        producer.shutdown();
    }
}
